/*!
* @author @huntbao
* @document helper functions
*/
App.itemHelper = {
	init: function(appView){
	   this.appView = appView;
	},
        
    initLeftMenu: function(){
        var self = this,
        appView = self.appView;
        appView.leftMenuItemCollection.add(
            [{
                id: appView.leftMenuIds.ownMe,
                url: '#!home',
                iconCls: 'icon_sider_document',
                name: App.i18n.get('fromOwnMe'),
                count: 0
            }, {
                id: appView.leftMenuIds.shareByMe,
                url: '#!share/shareByMe',
                iconCls: 'icon_sider_shareby',
                name: App.i18n.get('shareByMe'),
                count: 0
            }, {
                id: appView.leftMenuIds.publicMe,
                url: '#!public',
                iconCls: 'icon_sider_shareby',
                name: App.i18n.get('publicDoc'),
                count: 0
            }, {
                id: appView.leftMenuIds.shareForMe,
                url: '#!share/shareForMe',
                iconCls: 'icon_sider_sharefor',
                name: App.i18n.get('shareForMe'),
                count: 0
            }, {
                id: appView.leftMenuIds.recycleMe,
                url: '#!recycle',
                iconCls: 'icon_sider_recycle',
                name: App.i18n.get('recycle'),
                count: 0
            }]
        );
    },
        
    bindDrag: function(){
        var self = this;
        self.dragItems = self.appView.docList.find('.doc-item');
        self.dragItems.draggable({
            revert: 'invalid',
            helper: function () {
                return $("<div class='file-dragger-tip'></div>");
            },
            cursorAt: { top: 0, left: -20 },
            addClasses: false,
            start: function (e, ui) {
                var t = $(this);
                if(!t.hasClass('highlight')){
                   t.find('.inner-item').trigger('click');
                }else{
                   t.addClass('no-click-evt');
                }
                var selectedNum = self.appView.docList.find('.highlight').length;
                if (selectedNum === 1) {
                    ui.helper.text($(this).find('label').text());
                } else {
                    ui.helper.text(App.i18n.get('dragItemNum', [selectedNum]));
                }
            },
            stop: function (e) {
                $(this).removeClass('no-click-evt');
            },
            appendTo: 'body',
            scroll: false,
            refreshPositions: true,
            opacity: 0.8,
            delay: $.browser.msie ? 0 : 200
        });
    },
    
    bindDrop: function(){
        var self = this,
        hoverCls = 'drag-active',
        recycleId = App.util.getIdWithPrefix(self.appView.leftMenuIds.recycleMe),
        itemsDropping = function(dragger, target){
            if(target.is('#' + recycleId)){
                //drag items to recycle
                self.appView.deleteSelected();
            }else{
                //drag items to folders
                self.appView.moveItems(self.appView.getItemModelById($(target).attr('id')).get('id'), self.appView.contextMenuView.getSelectedIds().join(','));
            }
        }
        self.appView.docList.find('.folder-item').add('#' + recycleId).droppable({
            accept: self.dragItems,
            hoverClass: hoverCls,
            drop: function (e, ui) {
                var dragger = ui.draggable,
                t = $(this);
                t.removeClass('no-click-evt');
                if(!t.hasClass('highlight')){
                    itemsDropping(ui.draggable, t);
                }
            },
            over: function (e, ui) {
                var dragger = ui.draggable,
                t = $(this);
                if (t.hasClass('highlight')){
                    dragger.draggable('option', 'revert', true);
                }else{
                    dragger.draggable('option', 'revert', 'invalid');
                }
                t.addClass('no-click-evt');
            },
            tolerance: 'pointer',
            addClasses: false
        });
    },
	//remove item(folder or file) by json data(from server)
    removeItemsByData: function(data){
        var self = this,
        allItems = self.appView.docList.children(),
        removeItemsIds = [];
        _.each(data, function(item){
            removeItemsIds.push(item.id);
        });
        _.each(allItems, function(item, idx){
            var itemId = self.appView.getItemModelById($(item).attr('id')).get('id');
            if(removeItemsIds.indexOf(itemId) !== -1){
                $(item).slideUp(function(){
                    $(this).remove();
                    self.appView.itemCollection.remove(itemId);
                });
            }
        });
    },
    
    removeSelectedItems: function(){
        this.appView.docList.find('.highlight').removeClass('highlight');
    },

    selectAllItems: function(){
        var self = this;
        self.appView.docList.children().addClass('highlight');
        self.appView.updateHeaderBtn();
        return false;
    },
    
    removeCutStyle: function(){
        var self = this;
        self.appView.docList.find(".doc-item-cut").removeClass("doc-item-cut");
        return self;
    },
    
    removeSelectedEls: function(excludeIds){
        var self = this,
        items = self.appView.getActionParam().items;
        _.each(items, function(item, idx){
        	var model = self.appView.getItemModelById($(item).attr('id'));
            if(excludeIds && excludeIds.indexOf(model.get('id')) !== -1) return;
            $(item).slideUp(function(){
                if(idx === items.length - 1){
                    var next = $(items[idx]).next();
                    $(this).remove();
                    if(next.length > 0){
                        next.addClass('highlight');
                    }else{
                    	var first = self.appView.docList.children(0);
                    	if(first.length > 0){
                    	   first.addClass('highlight');
                    	}else{
                            self.appView.updateHeaderBtn();
                        }
                    }
                }else{
                    $(this).remove();
                }
            	self.appView.itemCollection.remove(model.get('id'));
            });
        });
    },
    
    getSelectedIds: function(isDeleteAction, isCutAction){
        var self = this,
        actionParam = self.appView.getActionParam();
        if(isDeleteAction){
            var canDeleteIds = [],
            canDeleteEls = [],
            cannotDeleteIds = [],
            cannotDeleteEls = [],
            model;
            _.each(actionParam.items, function(item){
                model = self.appView.getItemModelById($(item).attr('id'));
                if(model.get('folder') === true && model.get('count') > 0){
                    cannotDeleteIds.push(model.get('id'));
                    cannotDeleteEls.push($(item));
                }else{
                    canDeleteIds.push(model.get('id'));
                    canDeleteEls.push($(item));
                }
            });
            return{
                canDeleteIds: canDeleteIds,
                canDeleteEls: canDeleteEls,
                cannotDeleteIds: cannotDeleteIds,
                cannotDeleteEls: cannotDeleteEls
            }
        }else{
            var ids = [];
            if(isCutAction){
                App.itemHelper.removeCutStyle();
                _.each(actionParam.items, function(item){
                    $(item).addClass('doc-item-cut');
                    ids.push(self.appView.getItemModelById($(item).attr('id')).get('id'));
                });
            }else{
                _.each(actionParam.items, function(item){
                    ids.push(self.appView.getItemModelById($(item).attr('id')).get('id'));
                });
            }
            return ids;
        }
    },
        
    addShortCutKey: function(){
        var self = this,
        docList = self.appView.docList,
        removeSelected = function(){
            docList.find('.highlight').removeClass('highlight');
        },
        getSelected = function(){
            return docList.find('.highlight');
        },
        highLight = function(direction){
            if(!direction) return;
            var selected = getSelected();
            if(selected.length === 0){
                var first = docList.children().eq(0);
                if(!first.is('.mod-blank-list')){
                    first.addClass('highlight').find('.inner-item').trigger('click');
                }
            }else{
                var item = null;
                if(direction === 'prev'){
                    item = $(selected[0]).prev();
                }else if(direction === 'next'){
                    item = $(selected[selected.length - 1]).next();
                }else if(direction === 'prevrow'){
                    var thumbnailNumPerRow = Math.floor(docList.width() / 132);
                    var currentItem = $(selected[0]);
                    var children = docList.children();
                    item = $(children[children.index(currentItem) - thumbnailNumPerRow]);
                }else if(direction === 'nextrow'){
                    var thumbnailNumPerRow = Math.floor(docList.width() / 132);
                    var currentItem = $(selected[0])
                    var children = docList.children();
                    item = $(children[children.index(currentItem) + thumbnailNumPerRow]);
                }
                if(item && item.length > 0){
                    removeSelected();
                    item.addClass('highlight').find('.inner-item').trigger('click');
                    docList.stop(true, true).animate({scrollTop: item[0].offsetTop});
                }
            }
        },
        openSelected = function(){
            var selected = getSelected();
            if(selected.length === 1){
                selected.find('.inner-item').trigger('dblclick');
            }
        }
        $(document).bind('keydown.glodonsck', function(e){
            if(!$(e.target).is(':input')){
                var which = e.which;
                if(self.appView.isThumbMode()){
                    if(which === 37){
                        //left
                        highLight('prev');
                    }else if(which === 39){
                        //right
                        highLight('next');
                    }else if(which === 38){
                        //up
                        highLight('prevrow');
                    }else if(which === 40){
                        //down
                        highLight('nextrow');
                    }
                }else{
                    if(which === 38){
                        //up
                        highLight('prev');
                    }else if(which === 40){
                        //down
                        highLight('next');
                    }
                }
                //ctrl + a
                if((e.ctrlKey || e.metaKey) && which === 65){
                    self.selectAllItems();
                    return false;
                }
                //ctrl + b
                if((e.ctrlKey || e.metaKey) && which === 66){
                    self.toggleBrowseMode();
                }
                //ctrl + x
                if((e.ctrlKey || e.metaKey) && which === 88){
                    self.cutSelected();
                }
                //ctrl + v
                if((e.ctrlKey || e.metaKey) && which === 86){
                    self.pasteItems();
                }
                //F2
                if(which === 113){
                    self.renameItem();
                }
                //d for detail
                if(which === 68){
                    self.detailItem();
                }
                //enter
                if(which === 13){
                    openSelected();
                }
                //delete
                if((!e.ctrlKey && !e.metaKey && !e.shiftKey) && (which === 46 || which === 110)){
                    self.appView.deleteSelected();
                }
            }
        });
    },
        
    toggleBrowseMode: function(){
        var self = this;
        if(self.appView.isThumbMode()){
            $('#list_model').trigger('click');
        }else{
            $('#thumb_model').trigger('click');
        }
        return false;
    },
        
    cutSelected: function(){
        var self = this;
        self.appView.contextMenu.find('.cutItem').trigger('click');
        return false;
    },
        
    pasteItems: function(){
        var self = this;
        self.appView.docList.trigger('contextmenu');
        self.appView.contextMenu.find('.pasteItem').trigger('click');
        return false;
    },
        
    renameItem: function(){
        var self = this;
        self.appView.contextMenu.find('.renameItem').trigger('click');
        return false;
    },
        
    detailItem: function(){
        var self = this,
        actionParam = self.appView.getActionParam();
        if(!actionParam.fromOwnMe || actionParam.mutil || actionParam.isFolder) return false;
        self.appView.contextMenu.find('.detailItem').trigger('click');
        return false;
    },
        
    deleteAll: function(e){
        var self = this;
        $("#dialog").html( tpl.deleteDialog );
        var html = '<p>' + App.i18n.get('emptyRecycleConfirmTip') + '</p>';
        var dialog = $("#glodon_delete_dlg").modal({
            keyboard: true,
            show: true,
            backdrop: "static"
        });
        dialog.find('.text').html(html).end().find('.btn-ok').click(function(e){
            var t = $(this).button('loading');
            App.util.showTip(App.i18n.get('emptyingRecycleTip'));
            $.ajax({
                type : "delete",
                url : App.util.contextPath + "/recycler.json",
                success : function(e){
                    App.util.hideTip(App.i18n.get('emptiedRecycleTip'), 3000);
                    t.button('complete');
                    dialog.modal('hide');
                    self.appView.docList.empty();
                    self.appView.itemCollection.reset([]);
                    self.appView.updateHeaderBtn();
                    self.updateQuota();
                }
            });
        });
        return false;
    },
    
    updateQuota: function(){
        var self = this;
        $.get(App.util.contextPath + "/file/usedSpace.json", function(data){
            App.quota.used = data.space;
        });
    },
        
    getDownloadOption : function( model , nav ){
        var dataBagId = model.get("dataBagId");
        var extension = model.get("extension").toLowerCase();
        if( extension== "jpg" || extension== "png" || extension == "pdf"
                      || extension== "bmp" || extension== "gif" || extension== "png")
        {
            $(".downThereD").hide();
            $(".header_download").show();
        }
        else if( dataBagId )
        {
             $.ajax({
                 url : "/document/bag/"+ dataBagId +"/progress",
                 async : false,
                 success : function(response){
                     if( parseInt(response) < 100)
                     {
                         $(".header_download").show();
                     }
                     else if( parseInt(response) == 100 )
                     {
                         $(".downThereD").show();
                         $(".downloadas").unbind("click").bind('click',function(){
                             $(document).one('click.fancytooltip', function(e){
                                $("#downloadasMenu").hide(200);
                             });
                          $.ajax({
                            url: window._global.databagURL+"/bag/"+ dataBagId +"/path/manifest.json",
                                dataType: "json",
                                success : function(data){
                                    model.manifest = data;
                                    var defaultViewId = data.Metadata.DefaultView ,html = "",
                                      defaultView;
                                      
                                    html += "<li class=downloadOptions><span><a href="+window._global.contextPath 
                                             + '/file/download?id=' + model.get('id') + ">原始文件下载(*."+ model.get('extension') +")</a></span></li><li class=divider></li>";  
                                    for( var i=0 ; i < data.Views.length ; i++ )
                                    {
                                        if( data.Views[i].ID == defaultViewId )
                                        {
                                            defaultView = data.Views[i];
                                            break;
                                        }
                                    }
                                    for ( var j=0 ; j < defaultView.Representations.length ; j++)
                                    {
                                        if( defaultView.Representations[j].Downloadable)
                                        { 
                                            if( defaultView.Representations[j].Description )
                                            {
                                                html += "<li class=downloadOptions><span><a href="+window._global.databagURL+"/bag/"+model.get("dataBagId")+"/path/"+defaultView.Representations[j].Path+
                                                "?download=true>"+defaultView.Representations[j].Description+"</a></span></li>"
                                            }
                                            else
                                            {
                                                html += "<li class=downloadOptions><span><a href="+window._global.databagURL+"/bag/"+model.get("dataBagId")+"/path/"+defaultView.Representations[j].Path+
                                                "?download=true>"+defaultView.Name+"("+ defaultView.Representations[j].MIME.substr(defaultView.Representations[j].MIME.indexOf( '/' )+1) +")</a></span></li>"
                                            }
                                        }
                                    }
                                    
                                    $("#downloadasMenu .fancy-list").html( html );
                                    $("#downloadasMenu").show();
                                    $(".fancy-list .downloadOptions").hover(function(){
                                        $(this).addClass("highlighted");
                                    },function(){
                                        $(this).removeClass("highlighted");
                                    });
                                }
                                ,
                                error : function(){
                                    
                                }
                             });
                              return false;
                         })
                     }
                 }
                 ,
                 error : function(){
                     
                 }
            })
        }
        else
        {
            nav.find(".header_download").show();
        }
    }
}
 
